<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/4/23
 * Time: 11:56
 */

namespace App\Http\Controllers\Api\V1;


use App\Http\Resources\CategoryCollection;
use App\Http\Resources\TagCollection;
use App\Models\Category;
use App\Models\Doc;
use App\Models\DocArticle;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class DocEditController extends BaseController
{
    public function index()
    {
        $data['mode'] = [
            [
                'title' => '技术文档',
                'desc' => '编写专业知识文档/书籍等，可创建树形目录，只支持MarkDown格式编写',
                'src' => 'https://s.yundocs.cn/storage/public/jishu.png',
                'mode' => 'docs'
            ],
            [
                'title' => '文章集合',
                'desc' => '编写各种图文，音视频内容，适用于图文教程，帖子等，不可创建树形目录',
                'src' => 'https://s.yundocs.cn/storage/public/wenzhang.png',
                'mode' => 'articles'
            ]
        ];
        return $this->success($data);
    }

    /**
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function del_doc()
    {
        $user = $this->getUser();
        $id = $this->getId();
        $doc = Doc::query()->withAnyStatus()->where('user_id', $user->id)->findOrFail($id);

        $res = Doc::delDoc($doc);

        if ($res) {
            return $this->message("删除成功");
        }

    }

    /**
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function del_article()
    {
        $user = $this->getUser();
        $id = $this->getId();
        $article = DocArticle::query()->where('user_id', $user->id)->findOrFail($id);
        $res = $article->delete();
        if ($res) {
            return $this->message("删除成功");
        } else {
            return $this->failed("删除失败");
        }
    }


    public function before_edit()
    {
        $user = $this->getUser();
        $id = $this->getId('id', false);
        if ($id > 0) {
            $old = Doc::query()->withAnyStatus()->where('user_id', $user->id)->findOrFail($id);
            $data['doc'] = \App\Http\Resources\Doc::make($old)->type('edit');
            $data['tag_list'] = TagCollection::make($old->tags);
        }
        $category = Category::query()->orderByDesc('order')->get();
        $data['category'] = CategoryCollection::make($category)->type('mobile-edit');
        return $this->success($data);
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function edit_base(Request $request)
    {
        $data = $request->all();
        $user = $this->getUser();
        $id = $request->input("id", false);
        if ($id) {
            $id = hashid_decode($id);
            if ($id <= 0) {
                return $this->failed('id error');
            }
        }

        $validator = \Validator::make($data, [
            'title' => 'required|max:30',
            'mode' => ['required', Rule::in(['docs', 'articles'])],
            //'versions' => 'required',
            'abstract' => 'required|min:10|max:400',
            //'cover' => 'required',
            //'cover_id' => 'required',
            'doc_type' => ['required', 'boolean'],
            'money' => 'numeric',
            'resell_percent' => 'integer',
            'resell_enabled' => 'required|boolean',
            'category' => 'required|array',
            'tags' => 'array',
            //'nav_color' => 'required',
            //'font_color' => 'required|boolean',
        ], [
            'title.required' => '请输入标题',
            'mode.required' => '请输入模型',
            'abstract.required' => '请输入简介',
            'abstract.min' => '描述最少10个字',
            'abstract.max' => '描述最多400个字',
            'resell_percent.max' => '分销比率最大不能超过50',
            'resell_percent.min' => '分销比率最小不能低于1',
            'money.min' => '价格不能为0',
        ]);
        $validator->sometimes(['money'], 'min:0.01', function ($input) {
            return $input->doc_type == 1;
        });
        $validator->sometimes(['resell_percent'], 'min:1|max:50', function ($input) {
            return $input->resell_enabled == true;
        });
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $cover_id = $this->getId('cover_id', 0);
        $category = $request->input("category");
        $tags = $request->input("tags");
        $edit_data['title'] = $request->input("title");
        $edit_data['mode'] = $request->input("mode");
        $edit_data['versions'] = $request->input("versions", "-");
        $edit_data['abstract'] = $request->input("abstract");
        $edit_data['cover'] = $request->input("cover", null);
        $edit_data['cover_id'] = $cover_id;
        $edit_data['doc_type'] = $request->input("doc_type");
        $edit_data['money'] = $request->input("money");
        $edit_data['resell_percent'] = 0;//$request->input("resell_percent",0);
        $edit_data['resell_enabled'] = 0;//$request->input("resell_enabled",0);
        $edit_data['user_id'] = $user->id;
        $edit_data['nav_color'] = $request->input("nav_color", "#ffffff");
        $edit_data['font_color'] = $request->input("font_color", "#000000");
        $edit_data['category_id'] = last($category);
        if ($id > 0) {
            $doc = Doc::query()->withAnyStatus()->where('user_id', $user->id)->findOrFail($id);
            $doc->update($edit_data);
        } else {
            $edit_data['approved'] = config('approved_default', 0);
            $doc = Doc::query()->create($edit_data);
        }
        $tags_ids = collect($tags)->map(function ($item) {
            return hashid_decode($item);
        });
        $doc->tags()->sync($tags_ids);

        return $this->message('保存成功');
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function edit_cover(Request $request)
    {
        $data = $request->all();
        $user = $this->getUser();
        $id = $this->getId();
        $validator = \Validator::make($data, [
            'cover' => 'required',
            'cover_id' => 'required',
        ], [
            'cover.required' => '请上传图片',
            'cover_id.required' => '请上传图片',

        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $cover_id = $this->getId('cover_id');
        $edit_data['cover'] = $request->input("cover");
        $edit_data['cover_id'] = $cover_id;
        $doc = Doc::query()->withAnyStatus()->where('user_id', $user->id)->findOrFail($id);
        $doc->update($edit_data);
        return $this->message('保存成功');
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function before_edit_article(Request $request)
    {
        $doc_id = $this->getId('doc_id');
        $user = $this->getUser();
        $id = $this->getId();
        $doc = Doc::query()->withAnyStatus()->where('user_id', $user->id)->findOrFail($doc_id);
        $doc_article = DocArticle::query()->where('doc_id', $doc->id)->where('user_id', $user->id)->findOrFail($id);
        return $this->success(\App\Http\Resources\DocArticle::make($doc_article)->type('node-edit'));


    }

    public function edit_article(Request $request)
    {
        $data = $request->all();
        $doc_id = $this->getId('doc_id');
        $user = $this->getUser();
        $id = $request->input("id", false);
        if ($id) {
            $id = hashid_decode($id);
            if ($id <= 0) {
                return $this->failed('id error');
            }
        }
        $validator = \Validator::make($data, [
            'doc_id' => 'required',
            'title' => 'required|max:30',
            'content' => 'required|array',
            //'mode'=>['required',Rule::in(['node','html'])]
        ], [
            'title.required' => '请输入标题',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $content = json_encode($data['content']);


        $doc = Doc::query()->withAnyStatus()->where('user_id', $user->id)->findOrFail($doc_id);
        $edit_data['title'] = $data['title'];
        $edit_data['user_id'] = $user->id;
        $edit_data['doc_id'] = $doc->id;
        $edit_data['content'] = $content;
        $edit_data['cover'] = $data['cover'] ?? '';
        if ($id > 0) {
            $doc_article = DocArticle::query()->where('user_id', $user->id)->findOrFail($id);
            $doc_article->update($edit_data);
        } else {
            $edit_data['order'] = DocArticle::getOrder($doc->id);
            $doc_article = DocArticle::query()->create($edit_data);
        }
        return $this->message('保存成功');
    }

}